package Future;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class GetThreadRunTime2 implements Runnable {
	public static void main(String[] args) {
		ExecutorService executorService = Executors
				.newSingleThreadScheduledExecutor();//创建一个一定时间内只允许运行一个线程的的线程池
		GetThreadRunTime2 g2 = new GetThreadRunTime2();//创建线程
		executorService.execute(g2);//启动线程
		executorService.shutdown();//关闭线程池，不允许加入其他线程
		try {
		    final long begin = System.currentTimeMillis();//开始时间
			boolean flag = true;//时间监测标志
			while (flag) {
				boolean flagCurrent=executorService.awaitTermination(1, TimeUnit.SECONDS);// 每隔一秒监测线程运行是否结束
				System.out.println("flagCurrent="+flagCurrent);
				long end = System.currentTimeMillis();// 当前时间
				long CurrentRunTimes = (end - begin) / 1000;
				if (CurrentRunTimes >= 3) {//超过3秒
					//executorService.shutdownNow();
					flag = false;
				}
				System.out.println("运行了 " + CurrentRunTimes + "   秒");
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			Thread.sleep(50);
			System.out.println("two");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
